import React, { useState, useEffect } from 'react'
import { useParams, useSearchParams } from 'react-router-dom'
import { Card, message, Spin } from 'antd'
import { useAppSelector, useAppDispatch } from '@/store'
import { getScript } from '@/store/slices/scriptSlice'
import VersionManager from '@/components/Version/VersionManager'
import { Script } from '@/types/script'
import { Version } from '@/types/version'

const VersionHistory: React.FC = () => {
  const { scriptId } = useParams<{ scriptId: string }>()
  const [searchParams] = useSearchParams()
  const dispatch = useAppDispatch()
  
  const { scripts } = useAppSelector(state => state.script)
  
  // 状态管理
  const [script, setScript] = useState<Script | null>(null)
  const [currentVersion, setCurrentVersion] = useState<Version | null>(null)
  const [loading, setLoading] = useState(false)

  // 加载脚本信息
  const loadScript = async () => {
    if (!scriptId) {
      message.error('脚本ID不能为空')
      return
    }

    try {
      setLoading(true)
      
      // 先从store中查找
      let foundScript = scripts.find(s => s.id === scriptId)
      
      if (!foundScript) {
        // 从API加载
        const result = await dispatch(getScript(scriptId))
        if (result.payload) {
          foundScript = result.payload as Script
        }
      }
      
      if (foundScript) {
        setScript(foundScript)
        
        // 设置当前版本（如果有的话）
        if (foundScript.current_version) {
          setCurrentVersion(foundScript.current_version as any)
        }
      } else {
        message.error('脚本不存在')
      }
    } catch (error) {
      console.error('加载脚本失败:', error)
      message.error('加载脚本失败')
    } finally {
      setLoading(false)
    }
  }

  // 处理版本变化
  const handleVersionChange = (version: Version) => {
    setCurrentVersion(version)
    
    // 更新脚本信息
    if (script) {
      setScript({
        ...script,
        content: version.content,
        updated_at: version.created_at,
      })
    }
  }

  // 初始化
  useEffect(() => {
    if (scriptId) {
      loadScript()
    }
  }, [scriptId])

  if (loading) {
    return (
      <div style={{ 
        height: '100vh', 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center' 
      }}>
        <Spin size="large" />
      </div>
    )
  }

  if (!script) {
    return (
      <div style={{ padding: '24px' }}>
        <Card>
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            脚本不存在或加载失败
          </div>
        </Card>
      </div>
    )
  }

  return (
    <div style={{ 
      height: '100vh', 
      padding: '16px',
      background: '#f5f5f5',
    }}>
      <Card 
        title={`${script.name} - 版本管理`}
        style={{ height: '100%' }}
        bodyStyle={{ 
          padding: 0, 
          height: 'calc(100% - 57px)',
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        <VersionManager
          scriptId={script.id}
          currentVersion={currentVersion}
          onVersionChange={handleVersionChange}
          showCreateVersion={true}
        />
      </Card>
    </div>
  )
}

export default VersionHistory